import type {
  CreateCrudOptionsProps,
  CreateCrudOptionsRet,
  CrudExpose,
} from '@fast-crud/fast-crud';

import type { DefDatasourceConfigModel, FormRulesExt } from '#/api';
import type { ActionEnum } from '#/enums/commonEnum';

import { ref, unref } from 'vue';

import { useAccess } from '@vben/access';
import { $t } from '@vben/locales';

import { useLoading } from '@vben-core/shadcn-ui';

import { DefDatasourceConfigApi } from '#/api';
import { DictEnum } from '#/enums/commonEnum';
import { PermCode } from '#/enums/perm';
import { useMessage } from '#/hooks/web/useMessage';
import {
  backendDict,
  createdTimeColumn,
  deleteButton,
  indexColumn,
} from '#/plugins/fast-crud/common';

const { hasPermission } = useAccess();
const permCode = PermCode.devOperation.tenant.defDatasourceConfig;

export function createCrudOptions(
  props: CreateCrudOptionsProps<
    DefDatasourceConfigModel.DefDatasourceConfigResultVO,
    any
  >,
): CreateCrudOptionsRet<DefDatasourceConfigModel.DefDatasourceConfigResultVO> {
  const selectedRowKeys = ref<string[]>([]);
  const isTestConnect = ref(false);
  const { createMessage } = useMessage();
  const [openFullLoading, closeFullLoading] = useLoading({
    text: $t('common.loadingText'),
  });

  return {
    crudOptions: {
      request: {
        pageRequest: DefDatasourceConfigApi.pageRequest,
        addRequest: DefDatasourceConfigApi.addRequest,
        editRequest: DefDatasourceConfigApi.editRequest,
        delRequest: DefDatasourceConfigApi.delRequest,
        infoRequest: DefDatasourceConfigApi.infoRequest,
      },
      actionbar: {
        buttons: {
          add: {
            show: hasPermission(permCode.add),
          },
          ...deleteButton({
            crudExpose: props.crudExpose,
            selectedRowKeys,
            removeFn: DefDatasourceConfigApi.remove,
          }),
        },
      },
      table: {
        striped: true,
        rowKey: 'id',
        rowSelection: {
          type: 'checkbox',
          selectedRowKeys,
          onChange: (changed: string[]) => {
            selectedRowKeys.value = changed;
          },
        },
      },
      rowHandle: {
        width: '200px',
        buttons: {
          edit: {
            show: hasPermission(permCode.edit),
          },
          remove: {
            show: hasPermission(permCode.delete),
          },
          copy: {
            show: hasPermission(permCode.add),
          },
          debug: {
            show: hasPermission(permCode.test),
            text: '测试链接',
            dropdown: true,
            click(context) {
              if (unref(isTestConnect)) {
                createMessage.warning('正在测试连接，请稍后!');
                return;
              }

              const record = { ...context.row };
              record.poolName = 'test';
              isTestConnect.value = true;
              openFullLoading();
              DefDatasourceConfigApi.testConnect(record.id as string)
                .then((res) => {
                  if (res) {
                    createMessage.success('测试连接成功');
                  } else {
                    createMessage.error('测试连接失败,请检查配置是否正确!');
                  }
                })
                .finally(() => {
                  isTestConnect.value = false;
                  closeFullLoading();
                });
            },
          },
        },
      },
      columns: {
        ...indexColumn(props.crudExpose),
        name: {
          title: '名称',
          type: 'text',
          search: { show: true },
          column: {
            sorter: true,
            width: 180,
          },
        },
        username: {
          title: $t('devOperation.tenant.defDatasourceConfig.username'),
          type: 'text',
          search: { show: true },
        },
        password: {
          title: $t('devOperation.tenant.defDatasourceConfig.password'),
          type: 'password',
          column: { show: false },
          viewForm: { show: false },
        },
        url: {
          title: $t('devOperation.tenant.defDatasourceConfig.url'),
          type: 'text',
          search: { show: true },
          column: { ellipsis: { tooltip: true } },
        },
        driverClassName: {
          title: $t('devOperation.tenant.defDatasourceConfig.driverClassName'),
          type: 'dict-select',
          dict: backendDict(DictEnum.DATASOURCE_CONFIG_DRIVER),
          column: { ellipsis: { tooltip: true } },
        },
        ...createdTimeColumn({}),
      },
    },
  };
}

export const frontRules = (
  _crudExpose: CrudExpose,
  _mode: ActionEnum,
): FormRulesExt => {
  return {};
};
